<template>
  <div id="product-model-box">
    <div class="title-box">
      <div class="title">
        型号列表
      </div>
      <div class="button">
        <el-button type="primary" @click="addEmpty">新增型号</el-button>
      </div>
      <div class="c"></div>
    </div>
    <el-table
      v-if="isShowTable"
      max-height="550"
      size="mini"
      border
      stripe
      :style="{
        width:tableWidth+'px'
      }"
      :header-cell-style="{background:'#44739f',color:'#FFFFFF'}"
      :empty-text="emptyText"
      :data="currList"
      :row-class-name="tableRowClassName">
      <el-table-column
        prop="status"
        label="默认型号"
        width="100"
        align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isDefault" @change="changeDefault(scope.$index)"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-input-number :controls="false" @change="checkErrorRow" :min="0" :max="99999999" :step="0.01"
                           v-model="scope.row.price"
                           style="width: 90px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="nums"
        label="库存"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-input-number :controls="false" @change="checkErrorRow" @blur="checkNums(scope.$index)" :min="0"
                           :max="99999999" :step="1" v-model.number="scope.row.nums"
                           style="width: 90px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="score"
        label="兑换所需积分"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-input-number :controls="false" @change="checkErrorRow" @blur="checkNums(scope.$index)" :min="0"
                           :max="99999999" :step="1" v-model="scope.row.score"
                           style="width: 90px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="model"
        label="商品型号"
        width="380"
        align="center">
        <template slot-scope="scope">
          <el-input :maxlength="50" @change="checkErrorRow" v-model="scope.row.model" style="width: 350px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="image"
        label="图片"
        align="center"
        width="120">
        <template slot-scope="scope">
          <el-image style="width: 30px; height: 30px;" :src="showImage(scope.row.image)"
                    :preview-src-list="[showImage(scope.row.image)]"/>
          <el-upload
            class="avatar-uploader"
            :action="UploadFileUrl"
            :headers="getHeader()"
            name="myUploadFile"
            :show-file-list="false"
            :on-success="uploadImageSuccess">
            <span @click="changeImage(scope.$index)">上传图片</span>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column
        prop="groupPrice"
        label="团购价格"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-input-number @change="checkErrorRow" :controls="false" :step="0.01" :min="0" :max="99999999"
                           v-model="scope.row.groupPrice"
                           style="width: 90px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="groupNums"
        label="团购人数"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-input-number @change="checkErrorRow" @blur="checkNums(scope.$index)" :controls="false" :step="1" :min="0"
                           :max="100" v-model="scope.row.groupNums"
                           style="width: 90px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="commission"
        label="佣金(%)"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-input-number @change="checkCommission(scope)" :min="0" :step="1" :max="50" :controls="false"
                           v-model="scope.row.commission" style="width: 90px"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="120"
        align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" @change="changeStatus(scope.$index)"/>
        </template>
      </el-table-column>

      <el-table-column
        v-for="(item,_index) in productSpecifications"
        :label="item.name"
        :key="_index"
        width="120"
        align="center">
        <template slot-scope="scope">
          <!--自定义输入-类型-->
          <el-input v-if="getProductSpecifications(item.id).type.id===0"
                    v-model="scope.row['specifications-'+item.id]"
                    :maxlength="30"/>
          <!--选项-类型-->
          <el-select v-if="getProductSpecifications(item.id).type.id===1"
                     v-model="scope.row['specifications-'+item.id]">
            <el-option :value="sItem" :label="sItem"
                       v-for="(sItem,sIndex) in getProductSpecifications(item.id).itemList" :key="sIndex"></el-option>
          </el-select>

        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        width="100"
        align="center">
        <template slot-scope="scope">
          <el-button @click="remove(scope.$index)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <div class="error-info" v-if="errorInfo.length>0">
        <div class="item" v-for="(text,index) in errorInfo" v-text="text" :key="index"></div>
      </div>
    </div>
    <!--    <el-button type="primary" @click="submit">提交</el-button>-->

  </div>
</template>

<script>
export default {
  name: 'ProductModelBox',
  props: {
    initCurrList: Array,
    callBack: Function
  },
  data: function () {
    return {
      emptyText: '暂无数据',
      defaultModelNums: 100,
      currChangeImageIndex: -1,
      tableWidth: 1525,
      errorInfo: [],
      productSpecifications: [],
      currList: [
        // {
        //   id: 0,
        //   price: 100,
        //   model: '常规',
        //   nums: 100,
        //   image: '',
        //   groupNums: 0,
        //   groupPrice: 0,
        //   commission: 0,
        //   status: true,
        //   isDefault: true,
        //   isError: false
        // }
      ],
      isShowTable: true,
    }
  },
  mounted() {
    if (this.$props.initCurrList && this.$props.initCurrList.length > 0) {
      var list = []
      this.$props.initCurrList.forEach(function (value, index) {
        list.push({
          id: value.id,
          price: value.price,
          model: value.model,
          nums: value.nums,
          score: value.score,
          image: value.image ? value.image : '',
          groupNums: value.groupNums,
          groupPrice: value.groupPrice,
          commission: value.commission,
          specificationsData: value.specificationsData,
          status: value.status.id === 1,
          isDefault: value.isDefault.id === 1,
          isError: false
        })
      })
      // console.log('list',list)
      this.currList = list
      this.$forceUpdate()
    }
  },
  methods: {
    checkNums: function (index) {
      this.$set(this.currList[index], 'nums', this.toInt(this.currList[index].nums))
      this.$set(this.currList[index], 'score', this.toInt(this.currList[index].score))
      this.$set(this.currList[index], 'groupNums', this.toInt(this.currList[index].groupNums))
    },
    checkCommission: function (scope) {
      var index = scope.$index
      if (this.currList[index].commission < 0) {
        this.$set(this.currList[index], 'commission', 0)
      }
      if (this.currList[index].commission > 50) {
        this.$set(this.currList[index], 'commission', 50)
      }
    },
    getProductSpecifications: function (id) {
      let $this = this
      var item
      $this.productSpecifications.forEach(function (_value, _index) {
        if (_value.id === id) {
          item = _value
        }
      })
      return item
    },
    setProductSpecifications: function (productSpecifications) {
      let $this = this
      $this.isShowTable = false
      $this.productSpecifications = Object.assign([], productSpecifications)
      $this.productSpecifications.forEach(function (_value, _index) {
        if (_value.type.id === 1 && typeof _value.itemList === 'string') {
          _value.itemList = _value.itemList.split(',')
        }
      })
      setTimeout(function () {
        $this.setTableListSpecifications()
      }, 300)
    },
    setTableListSpecifications: function () {
      let $this = this
      $this.currList.forEach(function (value, index) {
        $this.productSpecifications.forEach(function (_value, _index) {
          if (value.specificationsData && value.specificationsData[_value.name]) {
            $this.$set($this.currList[index], 'specifications-' + _value.id, value.specificationsData[_value.name])
          } else {
            if (typeof value['specifications-' + _value.id] === 'undefined') {
              // 默认值
              if (_value.type.id === 1) {
                $this.$set($this.currList[index], 'specifications-' + _value.id, _value.itemList[0])
              } else {
                $this.$set($this.currList[index], 'specifications-' + _value.id, '')
              }
            }
          }
        })
      })
      $this.isShowTable = true
      $this.$forceUpdate()
    },
    showImage: function (image) {
      if (!image || image.length === 0) {
        return dict.NoImageURL
      } else {
        return image
      }
    },
    getCurrList: function () {
      var list = Object.assign([], this.currList)
      let $this = this
      list.forEach(function (value, index) {
        if (value.isDefault) {
          list[index].isDefault = 1
        } else {
          list[index].isDefault = 0
        }
        if (value.status) {
          list[index].status = 1
        } else {
          list[index].status = 0
        }
        var currSpecificationsData = {}
        if ($this.productSpecifications.length > 0) {
          $this.productSpecifications.forEach(function (_value, _index) {
            currSpecificationsData[_value.name] = value['specifications-' + _value.id] ? value['specifications-' + _value.id] : ''
            // delete list[index]['specifications-'+_value.id]
          })
        }
        list[index].specificationsData = currSpecificationsData
      })
      return list
    },
    getErrorInfo: function () {
      return this.errorInfo
    },
    checkErrorRow: function () {
      let $this = this
      var repeatModel = ''
      var groupError = false
      var groupNumsError = false
      var groupPriceOutError = false
      var isEmptyRow = false
      var isErrorPriceRow = false
      var isErrorScoreRow = false
      var isCommissionScoreRow = false
      var isErrorNumsRow = false
      var isErrorScoreRow2 = false
      var isErrorScoreDefaultRow = false
      $this.errorInfo = []
      var modelArr = []
      $this.currList.forEach(function (value, index) {
        if (value.score > 0) {
          $this.$set($this.currList[index], 'price', 0)
          $this.$set($this.currList[index], 'groupPrice', 0)
          $this.$set($this.currList[index], 'groupNums', 0)
        }
        // 检查重复型号
        if (modelArr.indexOf(value.model) > -1) {
          repeatModel = value.model
        }
        $this.$set($this.currList[index], 'isError', false)
        if (!value.model) {
          isEmptyRow = true
          $this.$set($this.currList[index], 'isError', true)
        }
        if (value.nums <= 0) {
          isErrorNumsRow = true
          $this.$set($this.currList[index], 'isError', true)
        }
        if (value.score > 0 && value.isDefault) {
          isErrorScoreDefaultRow=true
          $this.$set($this.currList[index], 'isError', true)
        }

        if (value.score < 0) {
          isErrorScoreRow = true
          $this.$set($this.currList[index], 'isError', true)
        }
        if (value.commission < 0 || value.commission > 50) {
          isCommissionScoreRow = true
          $this.$set($this.currList[index], 'isError', true)
        }
        if (value.price <= 0) {
          if (value.score === 0) {
            isErrorPriceRow = true
            $this.$set($this.currList[index], 'isError', true)
          }
        }
        if ((value.groupPrice > 0 || value.groupNums > 0) && (value.groupPrice === 0 || value.groupNums === 0)) {
          groupError = true
        }
        if (value.groupPrice > 0 && value.groupPrice >= value.price) {
          groupPriceOutError = true
        }
        if (value.groupNums === 1) {
          groupNumsError = true
        }
        if (value.groupNums > 1 && value.groupPrice > 0 && value.score > 0) {
          isErrorScoreRow2 = true
        }
      })

      // 错误提示文字
      if (isEmptyRow) {
        $this.errorInfo.push('【商品型号】不能为空')
      }
      // 错误提示文字
      if (isErrorScoreDefaultRow) {
        $this.errorInfo.push('【默认型号】不能【积分商品】')
      }
      if (repeatModel && repeatModel.length) {
        $this.errorInfo.push('【商品型号】不能重复')
      }
      if (isErrorPriceRow) {
        $this.errorInfo.push('【价格】不能小于等于0')
      }
      if (isErrorPriceRow) {
        $this.errorInfo.push('【佣金值】不能小于等于0，超过50%')
      }

      if (groupError) {
        $this.errorInfo.push('【团购价格和数量】,同时必须录入')
      }
      if (groupPriceOutError) {
        $this.errorInfo.push('【团购价格】必须小于【正常价格】')
      }
      if (groupNumsError) {
        $this.errorInfo.push('【团购人数】必须大于1')
      }
      if (isErrorNumsRow) {
        $this.errorInfo.push('【库存】不能小于等于0')
      }
      if (isErrorScoreRow) {
        $this.errorInfo.push('【积分】不能小于等于0')
      }
      if (isErrorScoreRow2) {
        $this.errorInfo.push('【积分】不能跟【团购】同时设置')
      }

      // 标记重复模型行,错误
      $this.currList.forEach(function (value, index) {
        if (value.model === repeatModel) {
          $this.$set($this.currList[index], 'isError', true)
        }
      })


      if ($this.currList.length === 1 && $this.currList[0].isDefault === false) {
        $this.$set($this.currList[0], 'isDefault', true)
        console.log('设置默认')
      }

      $this.$props.callBack($this.currList)
      $this.$forceUpdate()
    },
    tableRowClassName({row, rowIndex}) {
      if (row.isError) {
        return 'warning-row'
      }
      return ''
    },
    changeStatus: function (currIndex) {
      let $this = this
      if ($this.currList[currIndex].isDefault && !$this.currList[currIndex].status) {
        $this.$message.error('默认型号,不能设为【关闭状态】')
        setTimeout(function () {
          $this.$set($this.currList[currIndex], 'status', true)
        }, 500)
      }
    },
    changeDefault: function (currIndex) {
      let $this = this
      if ($this.currList[currIndex].isDefault) {
        // 设置默认
        $this.currList.forEach(function (value, index) {
          if (index !== currIndex) {
            $this.$set($this.currList[index], 'isDefault', false)
          }
        })
        // $this.$set($this.currList[currIndex],'isDefault',false)
      } else {
        // 取消默认
        var hasDefault = false
        $this.currList.forEach(function (value, index) {
          if (value.isDefault) {
            hasDefault = true
          }
        })
        if (!hasDefault) {
          $this.$set($this.currList[currIndex], 'isDefault', true)
        }
      }
      this.checkErrorRow()
    },
    uploadImageSuccess: function (res) {
      let $this = this
      setTimeout(function () {
        $this.$set($this.currList[$this.currChangeImageIndex], 'image', res.data)
      }, 500)
    },
    //
    changeImage: function (currChangeImageIndex) {
      this.currChangeImageIndex = currChangeImageIndex
    },
    // 移除单行
    remove: function (index) {
      if (this.currList.length > 0) {
        this.currList.splice(index, 1)
      } else {
        this.defaultModel = ''
      }
      this.checkErrorRow()
    },
    // 增加空行
    addEmpty: function () {
      var lastOne = this.currList[this.currList.length - 1]
      if (this.currList.length >= 10) {
        return this.$message.error('最大添加10行')
      }
      this.currList = this.currList.concat({
        id: 0,
        price: 0,
        model: '',
        nums: 0,
        score: 0,
        image: '',
        groupNums: 0,
        groupPrice: 0,
        commission: 0,
        status: true,
        isDefault: false,
        isError: true
      })
      this.setTableListSpecifications()
      this.checkErrorRow()
    },
  }
}
</script>

<style>
.el-table .el-table__row.warning-row {
  background: #ffe3e3;
}

.el-table--striped .el-table__body tr.el-table__row--striped.warning-row td.el-table__cell {
  background: #ffe3e3;
}

.error-info {
  background: #f8d8d7;
  padding: 10px;
  width: 300px;
  display: inline-block;
  border: 1px solid #e79e9e;
  margin: 5px;
  color: #e02323;
  line-height: 20px;
}

.error-info > .item {
  width: 100%
}

#product-model-box {
  min-height: 200px;
}

#product-model-box > .title-box {
  height: 40px;
  line-height: 40px;
  background: #f1f1f1
}

#product-model-box > .title-box > .title {
  float: left;
  width: 50%;
  text-align: left;
  text-indent: 10px;
}

#product-model-box > .title-box > .button {
  float: left;
  width: 48%;
  text-align: right;
}

.item-list {
}

.item-list > .item {
  float: left
}

.item-list > .item > .price {
  float: left;
  width: 15%
}

.item-list > .item > .model {
  float: left;
  width: 20%
}

.item-list > .item > .nums {
  float: left;
  width: 15%
}

.item-list > .item > .weight {
  float: left;
  width: 10%
}

.item-list > .item > .volume {
  float: left;
  width: 10%
}

.item-list > .item > .status {
  float: left;
  width: 10%
}
</style>
